package net.asrsmid.invoker;

import java.net.Authenticator;

import net.asrsmid.config.AsRsAuthMode;
import net.asrsmid.config.AsRsAuthenticator;
import net.asrsmid.connection.as.AsOlapConnection;
import net.asrsmid.invoker.as.Table;
import net.asrsmid.invoker.as.TableFactory;

import org.olap4j.CellSet;


/**
 * @author Chen WANG
 * @since 31 May 2011
 */
public class AsOlapInvoker {
	private AsOlapConnection conn;
	
	/**
	 * @param conn
	 */
	public AsOlapInvoker(AsOlapConnection conn) {
		this.conn = conn;
	}
	
	/**
	 * @return
	 */
	public AsOlapConnection getAsOlapConnection() {
		return conn;
	}
	
	public Table getTable(String mdxQuery) {
		return getTable(mdxQuery, null);
	}
	/**
	 * @param mdxQuery
	 * @return
	 */
	public Table getTable(String mdxQuery, AsRsAuthenticator auth) {
		Table table = null;
		try {
			if (auth != null && auth.getAuthMode() == AsRsAuthMode.BASIC) {
				Authenticator.setDefault(auth);
			}
			
			CellSet cellSet = conn.executeMdxQuery(mdxQuery);
			table = TableFactory.build(cellSet);
		} catch (Throwable t) {
			t.printStackTrace();
		} finally {
		    try {
		        // if (conn != null && !conn.isClosed())
		        conn.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
		}
		return table;
	}
}